/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dpy.appmvdpy.Facades;

import com.dpy.appmvdpy.Models.Users;
import java.util.List;
import javax.persistence.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author ac_psoares
 */
@Component
@org.springframework.context.annotation.Scope(value="request")
public class UsersFacade extends DefaultFacade<Users> {
    
    public UsersFacade()
    {
       super(Users.class);
    }

    @Override
    public void setId(Users entity) {
        entity.setUserId(this.getMaxId()+1);
    }
    
    @Override
    public int getMaxId()
    {
       Query q = super.em.createQuery("SELECT max(userId) from Users as c ");
       return q.getSingleResult() == null ? 0 : ((Number)q.getSingleResult()).intValue();  
    }    
    
    @Transactional
    public boolean existsUsers(String name)
    {        
       Query q = super.em.createQuery("SELECT u FROM Users u WHERE u.username = :username");
       q.setParameter("username", name);
       return q.getResultList().size() > 0;
    }  
    
     @Transactional
     public Users getByUsername(String name)
    {        
       Query q = super.em.createQuery("SELECT u FROM Users u WHERE u.username = :username");
       q.setParameter("username", name);
       return (Users)(q.getResultList().size() >= 1 ? q.getResultList().get(0) : null);
    }  
     
    @Override
    @Transactional(readOnly=true)
    public List<Users> listAll(int pag)
    {
       Query q = em.createQuery("SELECT c from Users as c WHERE c.username != 'admin'");
       q.setFirstResult(pag * 100);
       q.setMaxResults(100);
       return q.getResultList();
    }
    
    @Override
    @Transactional(readOnly=true)
    public List<Users> listAll()
    {
       Query q = em.createQuery("SELECT c from Users as c WHERE c.username != 'admin'");
       return q.getResultList();
    }
}
